package com.tisson.dict.pingserver.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;


@Component
public class PingTiming {
    private final WebClient webClient;
    private final RateLimiter rateLimiter;
    private static final Logger log = LoggerFactory.getLogger(PingTiming.class);

    public PingTiming(WebClient.Builder webClientBuilder, RateLimiter rateLimiter) {
        this.webClient = webClientBuilder.baseUrl("http://localhost:18081").build();
        this.rateLimiter = rateLimiter;
    }

    @Scheduled(fixedRate = 1000)
    public void sendPing() {
        if (rateLimiter.allowRequest()) {
            webClient.post()
                    .uri("/pong/answer")
                    .retrieve()
                    .toEntity(String.class)
                    .subscribe(
                            response -> log.info("Response: {}", response.getBody()),
                            error -> log.error("Error: ", error)
                    );
        } else {
            log.info("Rate limited");
        }
    }
}
